<template lang="pug">
  v-layout
    p(:style="{ background: '#fff', padding: '20px 0' }")
      v-checkbox(:indeterminate="indeterminate" v-model="allChecked" @click="checkAll") 全选
    p(:style="{ background: '#fff', padding: '10px 0' }")
      v-checkbox-group(:data="options" v-model="roles" @change="setState")
</template>
<script>
export default {
  name: 'systems-roles',
  data () {
    return {
      systemlist: [{value: '1', label: '区域1'}, {value: '2', label: '区域2'}],
      formData: {
        name: '',
        domain: '',
        path: ''
      },
      indeterminate: true,
      allChecked: false,
      roles: [],
      options: [],
      allRoles: []
    }
  },

  mounted () {
    this.getSystemRolePermissions()
  },
  methods: {
    getSystemRolePermissions () {
      let key = this.$route.params.system_key
      let id = this.$route.params.role_id
      this.$http.post(`rbac/system/${key}/role/${id}`).then(res => {
        let data = res.data
        for (let permission of data.permissions) {
          this.allRoles.push(permission._id)
          this.options.push({label: permission.permission_name, value: permission._id})
        }
        for (let rp of data.role_permissions) {
          this.roles.push(rp._id)
        }
      })
    },
    submitForm () {
      this.$http.post('rbac/role', this.formData)
        .then(res => {
          let result = res.data
          if (result.ret === 0) {
            this.$message.info(result.msg)
            this.formData = {
              name: '',
              domain: '',
              path: ''
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    checkAll () {
      if (this.roles.length === this.options.length) {
        this.roles = []
        this.allChecked = false
        this.indeterminate = false
      } else {
        this.roles = JSON.parse(JSON.stringify(this.allRoles))
        this.allChecked = true
        this.indeterminate = false
      }
    },
    setState () {
      this.indeterminate = this.roles.length > 0 && this.roles.length < this.options.length
      this.allChecked = this.roles.length === this.options.length
    }
  }
}
</script>
